package com.dpiinc.TechPage.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations.map
import androidx.lifecycle.Transformations.switchMap
import com.dpiinc.TechPage.api.NoteListApi
import com.dpiinc.TechPage.repository.SearchNoteRepository
import com.dpiinc.TechPage.room.RoomAiWriterDatabase
import com.dpiinc.TechPage.room.bean.LabelEntity

/**
 * 笔记搜索ViewModel
 * Created by X on 2018/7/28.
 */
class SearchViewModel(application: Application) : AndroidViewModel(application) {

    companion object {
        const val SEARCH_BY_CONTENT = 1
        const val SEARCH_BY_LABEL = 2
    }

    private val repository = SearchNoteRepository(RoomAiWriterDatabase.getInstance(application), NoteListApi.create())
    private val searchKeyword = MutableLiveData<String>()
    private var searchType = SEARCH_BY_CONTENT
    var currentKeyword: String = ""
    private val searchResult = map(searchKeyword) {
        repository.search(it, searchType)
    }

    val notes = switchMap(searchResult) { it.pagedList }!!

    val networkState = switchMap(searchResult) { it.networkState }!!
    val refreshState = switchMap(searchResult) { it.refreshState }!!

    val totalCount = switchMap(searchResult) { it.totalCount }!!

    fun loadLabels(): List<LabelEntity> {
        return repository.loadLabels()
    }


    fun search(keyword: String): Boolean {
        searchType = SEARCH_BY_CONTENT
        if (currentKeyword == keyword) {
            return false
        }
        currentKeyword = keyword
        searchKeyword.value = keyword
        return true
    }

    fun searchByLabel(labelId: String): Boolean {
        searchType = SEARCH_BY_LABEL
        if (currentKeyword == labelId) {
            return false
        }
        currentKeyword = labelId
        searchKeyword.value = labelId
        return true
    }

    fun retry() {
        val listing = searchResult?.value
        listing?.retry?.invoke()
    }
}